package system

import (
	"context"
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/system"
	systemReq "github.com/flipped-aurora/gin-vue-admin/server/model/system/request"
)

type GgProductService struct{}

// CreateGgProduct 创建ggProduct表记录
// Author [yourname](https://github.com/yourname)
func (ggProductService *GgProductService) CreateGgProduct(ctx context.Context, ggProduct *system.GgProduct) (err error) {
	err = global.GVA_DB.Create(ggProduct).Error
	return err
}

// DeleteGgProduct 删除ggProduct表记录
// Author [yourname](https://github.com/yourname)
func (ggProductService *GgProductService) DeleteGgProduct(ctx context.Context, id string) (err error) {
	err = global.GVA_DB.Delete(&system.GgProduct{}, "id = ?", id).Error
	return err
}

// DeleteGgProductByIds 批量删除ggProduct表记录
// Author [yourname](https://github.com/yourname)
func (ggProductService *GgProductService) DeleteGgProductByIds(ctx context.Context, ids []string) (err error) {
	err = global.GVA_DB.Delete(&[]system.GgProduct{}, "id in ?", ids).Error
	return err
}

// UpdateGgProduct 更新ggProduct表记录
// Author [yourname](https://github.com/yourname)
func (ggProductService *GgProductService) UpdateGgProduct(ctx context.Context, ggProduct system.GgProduct) (err error) {
	err = global.GVA_DB.Model(&system.GgProduct{}).Where("id = ?", ggProduct.Id).Updates(&ggProduct).Error
	return err
}

type ProductAndUser struct {
	Id int `json:"id"`
	system.GgUser
	system.GgProduct
}

// GetGgProduct 根据id获取ggProduct表记录
// Author [yourname](https://github.com/yourname)
func (ggProductService *GgProductService) GetGgProduct(ctx context.Context, id string) (ggProduct ProductAndUser, err error) {
	db := global.GVA_DB.Table("gg_user u").Select("u.*,p.*").Joins("join gg_product p on u.user_id=p.user_id")
	err = db.Where("u.user_id = ?", id).First(&ggProduct).Error
	return
}

// GetGgProductInfoList 分页获取ggProduct表记录
// Author [yourname](https://github.com/yourname)
func (ggProductService *GgProductService) GetGgProductInfoList(ctx context.Context, info systemReq.GgProductSearch) (list []ProductAndUser, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	//db := global.GVA_DB.Model(&system.GgProduct{})
	//var ggProducts []system.GgProduct
	db := global.GVA_DB.Table("gg_user u").Select("u.*,p.*").Joins("join gg_product p on u.user_id=p.user_id")
	// 如果有条件搜索 下方会自动创建搜索语句

	err = db.Count(&total).Error
	if err != nil {
		return
	}

	if limit != 0 {
		db = db.Limit(limit).Offset(offset)
	}

	err = db.Order("p.id desc").Find(&list).Error
	return list, total, err
}
func (ggProductService *GgProductService) GetGgProductPublic(ctx context.Context) {
	// 此方法为获取数据源定义的数据
	// 请自行实现
}
